package cn.cs.controller;

import cn.cs.client.*;
import cn.cs.common.*;
import cn.cs.pojo.*;
import cn.cs.service.ComplaintService;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*投诉接口*/
@RequestMapping("/complaint")
@RestController
public class ComplaintController {
    @Resource
    private ComplaintService complaintService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private TokenUtils tokenUtils;

    @Resource
    private CsPersonClient csPersonClient;

    @Resource
    private RestAppOrderClient appOrderClient;

    @Resource
    private SysDtAreaClient sysDtAreaClient;

    @Resource
    private AgentClient agentClient;

    /**
     * 平台客服接到投诉电话，添加投诉
     * @param complaint
     * @return
     * @throws Exception
     */
    @RequestMapping("/csPlatform/saveComplaint")
    @ResponseBody
    public Dto saveComplaint(@RequestBody Complaint complaint) throws Exception{
        String id = IdWorker.getId();
        String username = complaint.getUsername();
        CsPerson person = csPersonClient.findPersonByName(username);
        complaint.setId(id);
        complaint.setState("0");
        complaint.setType("电话投诉");
        complaint.setCreateDate(new Date());
        complaint.setCreateUser(person.getId());
        complaintService.itriptxAddComplaint(complaint);
        String repairUserId = complaint.getRepairUserId();

        Map<String, String> map = appOrderClient.getAreaIdByOrderId(complaint.getOrderId());
        if(EmptyUtils.isNotEmpty(map)){
            String area = map.get("areaId").toString();
            Map<String, Object> areaLast = sysDtAreaClient.getAreaLastById(area);
            if(EmptyUtils.isNotEmpty(areaLast)){
                area = areaLast.get("area_parent_id").toString();
            }
            List<Agent> agents = agentClient.getAgentByOnlyArea(area);


            // 发送极光推送给经销商
            String[] strSelect = new String[2];
            Map<String, String> cmap = new HashMap<String, String>();
            cmap.put("complaintId", id);
            for(int i = 0; i<agents.size(); i++){
                strSelect[i] = agents.get(i).getId();
            }
            Object obj = JPushUtil.testSendPushJXS(strSelect, "您旗下的维修工被投诉，请尽快处理", cmap);
            System.out.println(obj);
        }


        return DtoUtil.returnSuccess("投诉添加成功", complaintService.getAgentByRepairUserId(repairUserId));
    }

    /**
     * 分页查询投诉列表
     * @param pageNumber
     * @param pageSize
     * @param phone
     * @param repPhone
     * @param title
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/getComplaintPage")
    public Dto getComplaintPage(Integer pageNumber, Integer pageSize, String phone, String repPhone, String title, String startDate, String endDate) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("phone", phone);
        param.put("repPhone", repPhone);
        param.put("title", title);
        param.put("startDate", startDate);
        param.put("endDate", endDate);
        return DtoUtil.returnSuccess("获取成功", complaintService.queryComplaintPageByMap(param, pageNumber, pageSize));
    }


    /**
     * 投诉回访 -- 添加回访内容
     * @param id
     * @param returnVisit
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/customerReturnVisit")
    public Dto customerReturnVisit(String id, String returnVisit) throws Exception {
        Complaint complaint = new Complaint();
        complaint.setId(id);
        complaint.setReturnVisit(returnVisit);
        return DtoUtil.returnSuccess("操作成功", complaintService.itriptxModifyComplaint(complaint));
    }


    /**
     * 保存投诉()（不用）
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/csPlatform/addComplaint")
    @ResponseBody
    public Dto complain(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setHeader("Access-Control-Allow-Origin", "*");
        String token = request.getHeader("token");
        String userId = "";
        if(EmptyUtils.isEmpty(token)){
            return DtoUtil.returnSuccess("token空",false);
        }else{
            if(tokenUtils.validate("unknown",token)){
                //表示用户已经登录
                ClientUser clientUser= JSON.parseObject(redisUtils.get(token).toString(),ClientUser.class);
                userId = clientUser.getId();
            }else{
                return  DtoUtil.returnSuccess("不存在或者失效",false);
            }
        }
//            String clientUserId="1";
        String title=request.getParameter("title");
        String content=request.getParameter("content");
        String createTime=  DateUtil.format(new Date(),"yyyy-MM-dd hh:mm:ss");

        return complaintService.registerComplaint(request,userId,title,content,createTime);
    }


    /**
     * 投诉列表查询
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getComplaintList")
    @ResponseBody
    public Dto<Complaint> getComplaintList(String userId)throws  Exception {
        List<Complaint> list = complaintService.getComplaintByPhone(userId);
        return DtoUtil.returnSuccess("查询成功", list);
    }

    /**
     * 查询投诉详情
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/p/getComplaintById")
    @ResponseBody
    public Dto<Complaint> getComplaintById(String id)throws  Exception {
        Complaint complaint = complaintService.getComplaintById(id);
        return DtoUtil.returnSuccess("查询成功", complaint);
    }

    /**
     * 根据预约单id查询AB经销商信息
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/p/getAgentABByAppOrderId")
    @ResponseBody
    public Dto getAgentABByAppOrderId(String id)throws  Exception {
        AppOrder appOrder = appOrderClient.getAppOrderById(id);
        String area = appOrder.getAreaId();
        List<Agent> agent = agentClient.getAgentByOnlyArea(area);
        Map<String, Object> map1 = new HashMap<String, Object>();
        for(Agent a:agent){
            if("1".equals(a.getTypeId())){
                map1.put("AID", a.getId());
                map1.put("aPerson", a.getPerson());
                map1.put("aPhone", a.getPhone());
            }else{
                map1.put("BID", a.getId());
                map1.put("bPerson", a.getPerson());
                map1.put("bPhone", a.getPhone());
            }
        }

        return DtoUtil.returnSuccess("查询成功", map1);
    }

}
